import React, { useState, useEffect, useCallback } from "react";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Filter, Loader2 } from "lucide-react";
import { DictTypeAPI, DictDataAPI } from "@/api/dictionary";

export default function CrossingPointFilters({
  filters,
  onFilterChange,
  projects,
}) {
  // 新增状态管理
  const [crossingTypes, setCrossingTypes] = useState([]);
  const [isLoadingCrossingTypes, setIsLoadingCrossingTypes] = useState(true);
  const [loadingError, setLoadingError] = useState(null);

  // 获取跨越类型字典数据
  const loadCrossingTypeOptions = useCallback(async () => {
    try {
      setIsLoadingCrossingTypes(true);
      setLoadingError(null);

      // 1. 获取"跨越类型"字典类型信息
      const typeResponse = await DictTypeAPI.getList();

      // 查找目标字典类型
      const crossingType = typeResponse.rows?.find(
        (item) => item.dictName === "跨越类型"
      );

      // 2. 获取具体字典数据
      const dataResponse = await DictDataAPI.getList({
        dictType: crossingType.dictType,
      });

      // 格式化选项数据（确保value和label存在）
      const validTypes = (dataResponse.rows || [])
        .filter((item) => item.dictValue && item.dictLabel)
        .map((item) => ({
          value: item.dictValue,
          label: item.dictLabel,
        }));

      setCrossingTypes(validTypes);
    } catch (error) {
      console.error("加载跨越类型失败:", error);
      setLoadingError("无法加载跨越类型，请稍后重试");
    } finally {
      setIsLoadingCrossingTypes(false);
    }
  }, []);

  // 组件挂载时加载数据
  useEffect(() => {
    loadCrossingTypeOptions();
  }, [loadCrossingTypeOptions]);

  const handleFilterChange = (type, value) => {
    onFilterChange({
      ...filters,
      [type]: value,
    });
  };

  return (
    <div className="flex gap-3 flex-wrap">
      <div className="flex items-center gap-2">
        <Filter className="w-4 h-4 text-gray-500" />
        <Select
          value={filters.projectId || "all"}
          onValueChange={(value) => handleFilterChange("projectId", value)}
        >
          <SelectTrigger className="w-32">
            <SelectValue placeholder="项目" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">全部项目</SelectItem>
            {projects &&
              projects
                .filter(
                  (project) =>
                    project &&
                    project.id &&
                    project.projectName &&
                    project.id.trim() !== "" &&
                    project.projectName.trim() !== ""
                )
                .map((project) => (
                  <SelectItem key={project.id} value={project.id}>
                    {project.projectName}
                  </SelectItem>
                ))}
          </SelectContent>
        </Select>
      </div>

      <div className="flex items-center gap-2">
        <Select
          value={filters.crossingType || "all"}
          onValueChange={(value) => handleFilterChange("crossingType", value)}
          disabled={isLoadingCrossingTypes}
        >
          <SelectTrigger className="w-32">
            <div className="flex items-center">
              {isLoadingCrossingTypes && (
                <Loader2 className="w-4 h-4 mr-2 animate-spin text-gray-400" />
              )}
              <SelectValue placeholder="跨越类型" />
            </div>
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">全部类型</SelectItem>
            {crossingTypes.map((type) => (
              <SelectItem key={type.value} value={type.value}>
                {type.label}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
        {loadingError && (
          <span className="text-xs text-red-500">{loadingError}</span>
        )}
      </div>

      <div className="flex items-center gap-2">
        <Select
          value={filters.status || "all"}
          onValueChange={(value) => handleFilterChange("status", value)}
        >
          <SelectTrigger className="w-32">
            <SelectValue placeholder="状态" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">全部状态</SelectItem>
            <SelectItem value="Created">已创建方案</SelectItem>
            <SelectItem value="onCreated">未创建方案</SelectItem>
          </SelectContent>
        </Select>
      </div>

      <div className="flex items-center gap-2">
        <Select
          value={filters.priority || "all"}
          onValueChange={(value) => handleFilterChange("priority", value)}
        >
          <SelectTrigger className="w-32">
            <SelectValue placeholder="优先级" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">全部优先级</SelectItem>
            <SelectItem value="low">低</SelectItem>
            <SelectItem value="medium">中</SelectItem>
            <SelectItem value="high">高</SelectItem>
            <SelectItem value="urgent">紧急</SelectItem>
          </SelectContent>
        </Select>
      </div>

      <div className="flex items-center gap-2">
        <Select
          value={filters.difficultyLevel || "all"}
          onValueChange={(value) =>
            handleFilterChange("difficultyLevel", value)
          }
        >
          <SelectTrigger className="w-32">
            <SelectValue placeholder="难度" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">全部难度</SelectItem>
            <SelectItem value="low">低</SelectItem>
            <SelectItem value="medium">中</SelectItem>
            <SelectItem value="high">高</SelectItem>
            <SelectItem value="critical">极高</SelectItem>
          </SelectContent>
        </Select>
      </div>
    </div>
  );
}
